package com.iwinding.ladygg.ui.act.device;

import android.Manifest;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothProfile;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.iwinding.ladygg.R;
import com.iwinding.ladygg.bluetooth.BluetoothManager;
import com.iwinding.ladygg.bluetooth.ICaneBleRoutine;
import com.iwinding.ladygg.bluetooth.MyGattAttributes;
import com.iwinding.ladygg.bluetooth.bean.BleDevice;
import com.iwinding.ladygg.ui.act.BaseActivity;
import com.iwinding.ladygg.ui.adapter.CommonAdapter;
import com.iwinding.ladygg.ui.adapter.ViewHolder2;
import com.iwinding.ladygg.ui.view.ProDialogCreator;
import com.wang.avi.AVLoadingIndicatorView;

import java.util.ArrayList;
import java.util.List;

/**
 * 设备连接
 * Created by hezhiyong on 2017/3/14.
 */

public class OldDeviceActivity extends BaseActivity implements AdapterView.OnItemClickListener {
    //Debugging
    private static final String TAG = OldDeviceActivity.class.getSimpleName();

    public static final int REQUEST_CODE_ACCESS_COARSE_LOCATION = 1;

    private AVLoadingIndicatorView mAVsearch;
    private TextView mTvsearch;
    private View mLayDevice;
    private AVLoadingIndicatorView mAVDevice;
    private ListView lstv_devList;

    private String mRssi = null;
    private String connDeviceName;
    private String connDeviceAddress;
    private List<BleDevice> deviceList;
    private CommonAdapter<BleDevice> deviceAdapter;

    @Override
    protected int getLayoutID() {
        return R.layout.icane_activity_device;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        BluetoothManager.getInstance().stopScanDevice();
        super.onBackPressed();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == REQUEST_CODE_ACCESS_COARSE_LOCATION) {
            Log.i(TAG, "onRequestPermissionsResult: permissions.length = " + permissions.length +
                    ", grantResults.length = " + grantResults.length);
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // permission was granted, yay! Do the
                // contacts-related task you need to do.
                ProDialogCreator.getInstance().showDialog(getResources().getString(R.string.scanning));
                BluetoothManager.getInstance().
                        scanDevice();
            } else {
                // permission denied, boo! Disable the
                // functionality that depends on this permission.
                Toast.makeText(this, "位置访问权限被拒绝将无法搜索到ble设备", Toast.LENGTH_SHORT).show();
            }
        } else {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        initData();
    }

    void initView() {
        setBackTxtResId(R.string.bottom_tab_myself);
        setTitleResId(R.string.icane_my_connet);

        mAVsearch = (AVLoadingIndicatorView) findViewById(R.id.search_avload);
        mTvsearch = (TextView) findViewById(R.id.icane_txt_search);
        mLayDevice = findViewById(R.id.lay_device);
        mAVDevice = (AVLoadingIndicatorView) findViewById(R.id.device_avload);
        lstv_devList = (ListView) findViewById(R.id.device_listview);

    }

    void initData() {
        mTvsearch.setText(getString(R.string.icane_search_device, ""));

        ProDialogCreator.getInstance().initContext(this);
        initAdapter();
        lstv_devList.setOnItemClickListener(this);

        setBleDataListener();
        BluetoothManager.getInstance().initBleService();
        BluetoothManager.getInstance().setOnDataAvailableListener(ICaneBleRoutine.getInstance());
        BluetoothGatt gatt = BluetoothManager.getInstance().getConnBluetoothGatt();
        if(gatt==null){
            searchDevice();
        }else{
            setData(BluetoothManager.getInstance().getDeviceList());
        }
    }

    private void initAdapter() {
        serviceList = new ArrayList<>();
        characteristicList = new ArrayList<>();

        deviceList = new ArrayList<>();
        deviceAdapter = new CommonAdapter<BleDevice>(
                this, R.layout.icane_adapter_item_device, deviceList) {
            @Override
            public void convert(ViewHolder2 holder, final BleDevice device) {
                holder.setText(R.id.txtv_name, TextUtils.isEmpty(device.deviceName) ? "" : device.deviceName);
                holder.setText(R.id.txtv_address, TextUtils.isEmpty(device.deviceAddress) ? "" : device.deviceAddress);
                holder.setText(R.id.txtv_connState, device.isConnect ?
                        getResources().getString(R.string.state_connected) :
                        getResources().getString(R.string.state_disconnected));
                holder.setText(R.id.btn_connect, device.isConnect ?
                        getResources().getString(R.string.disconnected) :
                        getResources().getString(R.string.connected));
                holder.getView(R.id.btn_connect).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (device.isConnect) {
                            device.isConnect = false;
                            ProDialogCreator.getInstance().showDialog(getString(R.string.disconnecting));
                            BluetoothManager.getInstance().disconnDevice();
                        } else {
                            device.isConnect = true;
                            ProDialogCreator.getInstance().showDialog(getString(R.string.connecting));
                            connDeviceAddress = device.deviceAddress;
                            connDeviceName = device.deviceName;
                            BluetoothManager.getInstance().connDevice(connDeviceAddress);
                        }
                    }
                });
            }
        };
        lstv_devList.setAdapter(deviceAdapter);
    }


    /**
     * 搜索设备
     */
    void searchDevice() {
        mTvsearch.setText(getString(R.string.icane_search_device, String.valueOf(0)));
        mAVsearch.smoothToShow();
        mAVDevice.smoothToShow();
        //初始化
        deviceList.clear();
        verifyIfRequestPermission();
    }

    /**
     * 设置设备
     *
     * @param num
     */
    void setDeviceNum(int num) {
        mTvsearch.setText(getString(R.string.icane_search_device, String.valueOf(num)));
        mLayDevice.setVisibility(View.VISIBLE);
        mAVsearch.smoothToHide();
        mAVDevice.smoothToHide();
    }

    void setData(List<BleDevice> devices){
        deviceList.clear();
        deviceList.addAll(devices);
        deviceAdapter.notifyDataSetChanged();
        setDeviceNum(deviceList.size());
        ProDialogCreator.getInstance().dismissDialog();
        setManagerListener();
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //Ble数据回调
        final BleDevice device = deviceList.get((int) id);
        if (device.isConnect) {
            Intent intent = new Intent(mContext.getApplicationContext(), DeviceDetailActivity.class);
            intent.putExtra(DeviceDetailActivity.UUID, MyGattAttributes.SERVICE_FEATURES);
            intent.putExtra(DeviceDetailActivity.NAME, device.deviceName);
            intent.putExtra(DeviceDetailActivity.RSSI, device.deviceRssi);
            //如果是ICane则传输音量过去
            if (ICaneBleRoutine.getInstance().isHandshake())
                intent.putExtra(DeviceDetailActivity.VOLUME, ICaneBleRoutine.getInstance().getVolume());
            mContext.startActivity(intent);
        }

    }

    private void verifyIfRequestPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            Log.i(TAG, "onCreate: checkSelfPermission");
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_COARSE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED) {
                Log.i(TAG, "onCreate: Android 6.0 动态申请权限");
                if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                        Manifest.permission.READ_CONTACTS)) {
                    Log.i(TAG, "*********onCreate: shouldShowRequestPermissionRationale**********");
                    Toast.makeText(this, "只有允许访问位置才能搜索到蓝牙设备", Toast.LENGTH_SHORT).show();
                } else {
                    ActivityCompat.requestPermissions(this,
                            new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
                                    Manifest.permission.ACCESS_FINE_LOCATION},
                            REQUEST_CODE_ACCESS_COARSE_LOCATION);
                }
            } else {
                ProDialogCreator.getInstance().showDialog(getResources().getString(R.string.scanning));
                BluetoothManager.getInstance().scanDevice();
            }
        } else {
            ProDialogCreator.getInstance().showDialog(getResources().getString(R.string.scanning));
            BluetoothManager.getInstance().scanDevice();
        }
    }

    private List<BluetoothGattService> gattServiceList;
    private List<String> serviceList;
    private List<String[]> characteristicList;

    private void setBleDataListener(){
        BluetoothManager.getInstance().setmOnBleDeviceLinster(new BluetoothManager.OnBleDeviceLinster() {
            @Override
            public void obtainDevices(final List<BleDevice> devices) {

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        deviceList.clear();
                        deviceList.addAll(devices);
                        deviceAdapter.notifyDataSetChanged();
                        setDeviceNum(deviceList.size());
                        ProDialogCreator.getInstance().dismissDialog();
                        setManagerListener();
                    }
                });
            }
        });
    }

    private void setManagerListener(){
        BluetoothManager.getInstance().setOnBleManageListener(new BluetoothManager.OnBleManageListener() {
            @Override
            public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
                Log.i("@hzy","onConnectionStateChange-----"+newState);
                if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                    final String address = gatt.getDevice().getAddress();
                    //Ble连接已断开
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            for (BleDevice device:deviceList){
                                if(TextUtils.equals(device.deviceAddress,address)){
                                    device.isConnect = false;
                                }
                            }
                            ProDialogCreator.getInstance().dismissDialog();
                            deviceAdapter.notifyDataSetChanged();
                        }
                    });
                } else if (newState == BluetoothProfile.STATE_CONNECTING) {
                    //Ble正在连接
                } else if (newState == BluetoothProfile.STATE_CONNECTED) {
                    //Ble已连接
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ProDialogCreator.getInstance().dismissDialog();
                            deviceAdapter.notifyDataSetChanged();
                            ICaneBleRoutine.getInstance().setICaneConnBluetoothGatt();
                        }
                    });
                } else if (newState == BluetoothProfile.STATE_DISCONNECTING) {
                    //Ble正在断开连接
                }
            }

            @Override
            public void onServicesDiscovered(BluetoothGatt gatt, int status) {
                Log.i("@hzy","onServicesDiscovered-----"+status);
                if (status == BluetoothGatt.GATT_SUCCESS) {
//                    gattServiceList = gatt.getServices();
//                    serviceList.clear();
//                    for (BluetoothGattService service :
//                            gattServiceList) {
//                        String serviceUuid = service.getUuid().toString();
//                        serviceList.add(MyGattAttributes.lookup(serviceUuid, "Unknown") + "\n" + serviceUuid);
//                        Log.i(TAG, MyGattAttributes.lookup(serviceUuid, "Unknown") + "\n" + serviceUuid);
//
//                        List<BluetoothGattCharacteristic> characteristics = service.getCharacteristics();
//                        String[] charArra = new String[characteristics.size()];
//                        for (int i = 0; i < characteristics.size(); i++) {
//                            String charUuid = characteristics.get(i).getUuid().toString();
//                            charArra[i] = MyGattAttributes.lookup(charUuid, "Unknown") + "\n" + charUuid;
//                        }
//                        characteristicList.add(charArra);
//                    }
//                    final String address = gatt.getDevice().getAddress();
//                    for (BleDevice device:deviceList){
//                        if(TextUtils.equals(device.deviceAddress,address)){
//                            device.isConnect = true;
//                        }
//                    }
//                    deviceAdapter.notifyDataSetChanged();

                }
            }
        });
    }

}
